import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { HashingService } from 'src/module/authorization/hashingService';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly hashService: HashingService,
  ) {}

  async findAll(): Promise<Array<User> | any> {
    return this.userRepository.find();
  }

  // 根据地址查询用户
  async findUserByAddress(
    address: string,
    keywords: string,
  ): Promise<Array<User> | any> {
    if (keywords) {
      return this.userRepository
        .createQueryBuilder('user')
        .where('user.name like :keywords', { keywords: `%${keywords}%` })
        .andWhere('user.city = :city', { city: address })
        .getMany();
    } else {
      return this.userRepository
        .createQueryBuilder('user')
        .where('user.city = :city', { city: address })
        .getMany();
    }
  }

  // 分页查询数据
  async skipFind(
    currentPage: number,
    pageSize: number,
    role: string,
    city: string,
    keywords?: string,
  ): Promise<Array<User> | any> {
    let list = null;
    if (keywords) {
      list = await this.userRepository
        .createQueryBuilder('user')
        .where('user.role = :role', { role: role })
        .andWhere('user.isDelete = :isDelete', { isDelete: false })
        .andWhere('user.city = :city', { city: city })
        .andWhere('user.name LIKE :name', { name: `%${keywords}%` })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.userRepository
        .createQueryBuilder('user')
        .where('user.role = :role', { role: role })
        .andWhere('user.isDelete = :isDelete', { isDelete: false })
        .andWhere('user.city = :city', { city: city })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    }

    return {
      list: list[0],
      total: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }
  // 获取当前用户的数据
  async findOne(id: number): Promise<User> {
    return this.userRepository.findOne({ where: { id } });
  }

  // 根据userId 查询订单信息
  async findUserOrder(userId: number) {
    const res = await this.userRepository.find({
      select: [],
      relations: ['order'],
      where: { id: userId },
    });

    console.log('🚀 ~ This is a result of console.log ~ ✨: ', res);
    return res;
  }

  // 修改用户数据
  update(updateUserDto: UpdateUserDto) {
    const user = this.userRepository.create(updateUserDto);
    return this.userRepository.save(user);
  }

  // 修改密码
  async updatePassword(id, password) {
    const hashPassword = await this.hashService.hash(password);
    await this.userRepository.update(id, {
      password: hashPassword,
    });
    const user = await this.userRepository.findOne({ where: { id } });
    return { pri_id: user.primary_id };
  }

  // 根据id删除用户
  remove(ids: number[]) {
    ids.forEach(async (id) => {
      try {
        await this.userRepository
          .createQueryBuilder()
          .update(User)
          .set({
            isDelete: true,
          })
          .where('id = :id', { id: id })
          .execute();
      } catch (e) {
        console.log('🚀 ~ This is a result of console.log ~ ✨: 删除失败', id);
      }
    });
    return;
  }
}
